<template>
  <div>
    <div class="chart" id="oneChart">
      <span>图表加载中...</span>
    </div>
  </div>
</template>
  
  <script>
import { inject, onMounted, reactive, defineEmits } from "vue";
export default {
  setup() {
    let $echarts = inject("echarts");
    // 引用后台数据
    let $http = inject("axios");
    // 创建数据
    let data = reactive({});
    let xdata = reactive([]);
    let ydata = reactive([]);

    // 处理数据
    function setData() {
      xdata = data.data.chartData.chartData.data.map(v => v.title);
      ydata = data.data.chartData.chartData.data.map(v => v.num);
    }

    // 请求后台数据
    async function getState() {
      data = await $http({ url: "/one/data" });
    }

    onMounted(() => {
      // 获取元素
      let mychart = $echarts.init(document.getElementById("oneChart"));
      // 调用请求
      getState().then(() => {
        setData();
        // 初始化
        mychart.setOption({
          title: {
            subtext: "单位：百万",
            subtextStyle: {
              color: "#fff"
            }
          },
          grid: {
            left: "1%",
            right: "1%",
            bottom: "1%",
            containLabel: true
          },
          legend: {
            right: "top",
            textStyle: {
              color: "#fff"
            }
          },
          textStyle: {
            color: "#fff",
            fontSize: 15
          },
          dataset: {
            source: [
              ["product", "营业收入", "营业成本", "净利润"],
              ["2020", 430.3, 750.8, 430.7],
              ["2021", 730.1, 703.4, 550.1],
              ["2022", 760.4, 650.2, 720.5]
            ]
          },
          xAxis: { type: "category" },
          yAxis: {},

          series: [{ type: "bar" }, { type: "bar" }, { type: "bar" }]
        });
      });
    });
    return {
      // 返回数据
      getState,
      data,
      xdata,
      ydata,
      setData
    };
  }
};
</script>
  
  <style lang="scss" scoped>
.chart {
  height: 210px;
}
</style>